import json
import logging
from datetime import datetime
from typing import Dict, List
from fastapi import WebSocket
from demo.models.schemas import MessageType, DeviceStatus, ChatRequest
from demo.services.device_service import DeviceService
from demo.services.ai_service import AIChatService
from demo.websocket.manager import ConnectionManager
from openai import OpenAI

from like.websocket.messagehandler import MessageHandler
from like.websocket.schemas import DataType

logger = logging.getLogger(__name__)


class WebSocketMessageHandler:
    def __init__(self, connection_manager: ConnectionManager, device_service: DeviceService, ai_service: AIChatService,client:OpenAI,message_handler :MessageHandler):
        self.connection_manager = connection_manager
        self.device_service = device_service
        self.ai_service = ai_service
        self.client = client  # 使用全局的客户端实例
        self.msg_handler = message_handler
        logger.info("WebSocketMessageHandler 初始化完成，AI客户端已配置")

    async def handle_message(self, device_id: str, message_dict: dict, websocket: WebSocket):
        """处理WebSocket消息"""
        message_type = message_dict.get("type")
        message_data = message_dict.get("data", {})

        # 处理时间戳
        timestamp_str = message_dict.get('timestamp')
        timestamp = datetime.fromisoformat(timestamp_str) if timestamp_str else datetime.now()

        logger.info(f"收到来自设备 {device_id} 的消息: {message_type}")

        print(str(message_dict))

        if message_type == MessageType.DEVICE_REGISTER.value:
            await self._handle_device_register(device_id, message_data, websocket)
        elif message_type == MessageType.DATA_REPORT.value:
            await self._handle_data_report(device_id, message_data, websocket)
        elif message_type == MessageType.AI_CHAT.value:
            await self._handle_ai_chat(device_id, message_dict, websocket)
        elif message_type == MessageType.HEARTBEAT.value:
            await self._handle_heartbeat(device_id, message_data, websocket)
        else:
            await self._handle_unknown_message(device_id, message_type, websocket)

    async def _handle_device_register(self, device_id: str, message_data: Dict, websocket: WebSocket):
        """处理设备注册"""
        device_status = DeviceStatus(
            deviceId=device_id,
            versionName=message_data.get("versionName"),
            url=message_data.get("url"),
            code=message_data.get("code")
        )

        logger.info(f"设备注册: {device_status}")

        # 注册设备
        success = await self.device_service.register_device(device_status)

        # 发送响应
        response = {
            "type": MessageType.STATUS_UPDATE.value,
            "data": {
                "status": "registered" if success else "failed",
                "message": "设备注册成功" if success else "设备注册失败",
                "deviceId": device_id
            },
            "timestamp": datetime.now().isoformat()
        }
        await websocket.send_text(json.dumps(response))

    async def _handle_data_report(self, device_id: str, message_data: Dict, websocket: WebSocket):
        """处理数据报告"""
        content = message_data.get('content', '')
        logger.info(f"设备 {device_id} 数据：{content}")

        # 处理数据点
        #await self.device_service.process_data_points(device_id, data_points)

        #处理消息

        # # 发送确认响应
        # response = {
        #     "type": MessageType.STATUS_UPDATE.value,
        #     "data": {
        #         "status": "data_received",
        #         "message": f"成功接收 {content} 数据",
        #         "deviceId": device_id
        #     },
        #     "timestamp": datetime.now().isoformat()
        # }
        # await websocket.send_text(json.dumps(response))

        # 存储消息
        print(f"message_data==={str(message_data)}")
        # platform_type = message_dict.get("platform_type")
        data_type = message_data.get("data_type", -1)

        print(f"data_type==={data_type}")

        if not data_type:
            print("Missing data_type field")
            return {"error": "Missing data_type field"}

        self.msg_handler.process_message(message_data)


    async def _handle_ai_chat(self, device_id: str, message_data: Dict, websocket: WebSocket):
        """处理AI对话"""
        print(f"_handle_ai_chat=={str(message_data)}")
        user_message = message_data.get('message', '')
        logger.info(f"设备 {device_id} AI对话请求: {user_message}")

        try:
            # 使用真实的AI服务
            ai_response = await self.chat_completion(user_message)

            # 同时更新对话历史（可选）
            chat_history = self.connection_manager.get_chat_history(device_id)
            updated_history = chat_history.copy()
            updated_history.extend([
                {
                    "role": "user",
                    "content": user_message,
                    "timestamp": datetime.now().isoformat()
                },
                {
                    "role": "assistant",
                    "content": ai_response,
                    "timestamp": datetime.now().isoformat()
                }
            ])

            # 限制历史记录长度
            if len(updated_history) > 10:
                updated_history = updated_history[-10:]

            self.connection_manager.update_chat_history(device_id, updated_history)

            # 发送AI回复
            response = {
                "type": MessageType.AI_CHAT.value,
                "data": {
                    "role": "assistant",
                    "message": ai_response,
                    "timestamp": datetime.now().isoformat()
                },
                "timestamp": datetime.now().isoformat()
            }

            logger.info(json.dumps(response))
            await websocket.send_text(json.dumps(response))

        except Exception as e:
            logger.error(f"AI对话处理失败: {str(e)}")
            # 发送错误响应
            error_response = {
                "type": MessageType.AI_CHAT.value,
                "data": {
                    "role": "assistant",
                    "message": "抱歉，AI服务暂时不可用，请稍后重试。",
                    "timestamp": datetime.now().isoformat()
                },
                "timestamp": datetime.now().isoformat()
            }
            await websocket.send_text(json.dumps(error_response))

    async def chat_completion(self, user_message: str) -> str:
        """调用真实的AI服务"""
        try:
            chat_request = ChatRequest(message=user_message)

            # 调用硅基流动 API
            response = self.client.chat.completions.create(
                model=chat_request.model,
                messages=[
                    {"role": "user", "content": chat_request.message}
                ],
                max_tokens=chat_request.max_tokens,
                temperature=chat_request.temperature,
                stream=False
            )

            # 提取回复内容
            return response.choices[0].message.content

        except Exception as e:
            logger.error(f"AI API调用失败: {str(e)}")
            return f"AI服务暂时不可用: {str(e)}"

    async def _handle_heartbeat(self, device_id: str, message_data: Dict, websocket: WebSocket):
        """处理心跳"""
        logger.debug(f"设备 {device_id} 心跳检测")
        await self.device_service.update_device_status(device_id, "active")

        response = {
            "type": MessageType.STATUS_UPDATE.value,
            "data": {"status": "alive", "deviceId": device_id},
            "timestamp": datetime.now().isoformat()
        }
        await websocket.send_text(json.dumps(response))

    async def _handle_unknown_message(self, device_id: str, message_type: str, websocket: WebSocket):
        """处理未知消息类型"""
        logger.warning(f"未知消息类型: {message_type}")
        response = {
            "type": MessageType.STATUS_UPDATE.value,
            "data": {"status": "error", "message": "未知的消息类型"},
            "timestamp": datetime.now().isoformat()
        }
        await websocket.send_text(json.dumps(response))


    #指定设备发送消息
    async def send_to_device(self, device_id: str, message: Dict):
        """向指定设备发送消息"""
        if device_id in self.connection_manager.active_device_connections:
            try:
                websocket = self.connection_manager.active_device_connections[device_id]
                await websocket.send_text(json.dumps(message))
                return True
            except Exception as e:
                logger.error(f"向设备 {device_id} 发送消息失败: {e}")
                self.connection_manager.disconnect_device(device_id)
                return False
        else:
            logger.warning(f"设备 {device_id} 未连接")
            return False

    async def broadcast(self, message: Dict, exclude_devices: List[str] = None):
        """向所有设备广播消息"""
        if exclude_devices is None:
            exclude_devices = []

        disconnected_devices = []
        for device_id, websocket in self.active_connections.items():
            if device_id not in exclude_devices:
                try:
                    await websocket.send_text(json.dumps(message))
                except Exception as e:
                    logger.error(f"广播到设备 {device_id} 失败: {e}")
                    disconnected_devices.append(device_id)

        # 清理断开连接的设备
        for device_id in disconnected_devices:
            self.disconnect_device(device_id)